from rest_framework import viewsets, mixins
from rest_framework.decorators import list_route
from rest_framework.response import Response
from django.core.cache import cache

from users.models import UserModel
from users.serializers import UserSerializer, RegisterSerializer, LoginSerialzier
from utils.authentication import UserAuthentication
from utils.errors import ParamsException



class UserView(viewsets.GenericViewSet,
               mixins.ListModelMixin):
    # 资源数据
    queryset = UserModel.objects.all()
    # 序列化
    serializer_class = UserSerializer
    # 认证类
    authentication_classes = (UserAuthentication,)


    def list(self, request, *args, **kwargs):
        """
            前端需要结构为：
            {
                code: 200,
                msg: '',
                data: {
                    user_info: {
                        u_username: 'coco'
                    }
                    orders_not_pay_num: 0
                    orders_not_send_num: 0
                }
            }
        """
        # request.GET.get('token')  request.query_params.get('token')
        # token = request.query_params.get('token')
        # user_id = cache.get(token)
        # user = UserModel.objects.get(pk=user_id)
        user = request.user
        serializer = self.get_serializer(user)
        res = {
            'user_info': serializer.data,
            'orders_not_pay_num': 0,
            'orders_not_send_num': 0
        }
        return Response(res)


    @list_route(methods=['POST'], serializer_class=RegisterSerializer)
    def register(self, request):
        # 该方法要被调用，请求地址为: /api/user/auth/register/
        # 校验POST传递的参数
        serializer = self.get_serializer(data=request.data)
        # 判断校验结构
        result = serializer.is_valid(raise_exception=False)
        if not result:
            error = serializer.errors
            raise ParamsException({'code': 1005,
                                   'msg': '注册字段有误，请重新填写注册信息',
                                   'data': error})
        # result = serializer.is_valid()
        # if not result:
        # 校验字段没问题，且账号和密码也没问题
        user = serializer.save()

        # result = {
        #     'code': 200,
        #     'msg': '请求成功',
        #     'data': {
        #         'user_id': user.id
        #     }
        # }
        result = {
            'user_id': user.id
        }
        return Response(result)

    @list_route(methods=['POST'], serializer_class=LoginSerialzier)
    def login(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 如果执行以下的代码，则表示账号存在，且密码没问题
        token = serializer.login_user(serializer.data)
        res = {
            'token': token
        }
        return Response(res)


